package com.meryl.dtk;

import com.intellij.ide.IdeView;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.meryl.dtk.dialog.EntityDlg;
import com.meryl.dtk.dialog.ServiceDlg;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author : Meryl
 * @Description:
 * @Date: Created in 2024/9/11 17:45
 */
public class CreateEntityAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();

        IdeView ideView = e.getRequiredData(LangDataKeys.IDE_VIEW);
        PsiDirectory directory = ideView.getOrChooseDirectory();
        VirtualFile dirPath = directory.getVirtualFile();
        String path = dirPath.getPath();

        String packageName = path.substring(path.indexOf("java") + 5).replace("/", ".");

        String defaultBaseClassName = "com.extm.activerecord.Entity";

        String key = "ExtmEntityBaseClass";
        String jdsBaseClassStore = PropertiesComponent.getInstance().getValue(key);

        EntityDlg entityDlg = new EntityDlg();
        if (entityDlg.getTxtBaseClass() != null) {
            entityDlg.getTxtBaseClass().setText(defaultBaseClassName);
            if (jdsBaseClassStore != null && !jdsBaseClassStore.isBlank() && !jdsBaseClassStore.isEmpty()) {
                entityDlg.getTxtBaseClass().setText(jdsBaseClassStore);
            } else {
                entityDlg.getTxtBaseClass().setText(defaultBaseClassName);
            }
        }

        DialogBuilder dialogBuilder = new DialogBuilder(project);
        dialogBuilder.setCenterPanel(entityDlg.getRootPanel());
        dialogBuilder.setTitle("Create Entity");
        dialogBuilder.show();

        if (dialogBuilder.getDialogWrapper().getExitCode() == DialogWrapper.CANCEL_EXIT_CODE) {
            return;
        }

        String baseClassName = entityDlg.getTxtBaseClass().getText();
        if (baseClassName == null || baseClassName.isEmpty() || baseClassName.isBlank()) {
            baseClassName = defaultBaseClassName;
        }
        String baseClassShortName = baseClassName.substring(baseClassName.lastIndexOf(".") + 1);

        if (!baseClassName.equals(defaultBaseClassName)) {
            PropertiesComponent.getInstance().setValue(key, baseClassName);
        } else {
            PropertiesComponent.getInstance().setValue(key, null);
        }

        String entityName = entityDlg.getTxtEntityName().getText();
        if (entityName == null || entityName.isEmpty() || entityName.isBlank()) {
            Messages.showErrorDialog(new String("Please input entity name".getBytes(), StandardCharsets.UTF_8), "Error");
            return;
        }

        if (!packageName.contains("module")) {
            Messages.showErrorDialog("The Jds module is not included in the project. Please create the Jds module first", "Error");
            return;
        }

        String classText = "package " + packageName + ";\n" +
                "\n" +
                "import " + baseClassName + ";\n" +
                "import lombok.Data;\n" +
                "\n" +
                "@Data\n" +
                "public class " + entityName + " extends " + baseClassShortName + "<" + entityName + "> {\n" +
                "}\n";

        WriteCommandAction.runWriteCommandAction(project, () -> {
            try {
                PsiDirectoryFactory.getInstance(project)
                        .createDirectory(dirPath)
                        .createFile(entityName + ".java")
                        .getVirtualFile()
                        .setBinaryContent(classText.getBytes(StandardCharsets.UTF_8));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }
}
